package com.core.cloudbusiness.tool;

import com.alibaba.fastjson.JSON;
import com.core.cloudbusiness.system.user.mapper.CloudSystemUserMapper;
import com.core.cloudcommon.redis.service.CloudRedisTemplateService;
import com.core.cloudcommon.redis.vo.CloudRedisVO;
import com.core.cloudcommon.security.JwtTokenUtil;
import com.core.cloudcommon.security.UserInfo;
import com.core.cloundbusinessapi.system.login.dto.CloudSystemLoginDTO;
import com.core.cloundbusinessapi.system.user.dto.CloudSystemUserDTO;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author =====Lqj=====
 * @className CommonHeaderInterceptor
 * @description
 * @create 2024/12/4 16:00
 **/
@Component
@WebFilter("/api/*")
public class CommonHeaderInterceptor extends OncePerRequestFilter {

    @Autowired
    private CloudRedisTemplateService cloudRedisTemplateService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private CloudSystemUserMapper cloudSystemUserMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 排除 "/api/login" 登录接口
        if (request.getRequestURI().equals("/api/cloud/sys/login") || request.getRequestURI().equals("/api/cloud/sys/sendSms") ) {
            filterChain.doFilter(request, response);
            return;
        }
        // 从请求头中获取 token
        String token = request.getHeader("token");
        if (token != null && !token.isEmpty()) {
            try {
                // 使用JWT解析用户信息
                if (!jwtTokenUtil.isTokenExpired(token)) {
                    UserInfo userInfo = jwtTokenUtil.getUserFromToken(token);
                    // 根据用户ID查询完整的用户信息
                    CloudSystemUserDTO cloudSystemUserDTO = cloudSystemUserMapper.selectById(userInfo.getId());
                    if (cloudSystemUserDTO != null) {
                        CommonRequestContext.setUser(cloudSystemUserDTO);
                    }
                }
            } catch (Exception e) {
                // JWT解析失败，尝试从Redis获取（兼容旧token）
                try {
                    Object o = cloudRedisTemplateService.get(new CloudRedisVO(token));
                    if (Objects.nonNull(o)) {
                        CloudSystemLoginDTO cloudSystemLoginDTO = JSON.parseObject(o.toString(), CloudSystemLoginDTO.class);
                        CloudSystemUserDTO cloudSystemUserDTO = cloudSystemLoginDTO.getCloudSystemUserDTO();
                        CommonRequestContext.setUser(cloudSystemUserDTO);
                    }
                } catch (Exception ex) {
                    // 忽略错误，继续处理请求
                }
            }
        }
        // 继续处理请求
        filterChain.doFilter(request, response);
        CommonRequestContext.clearUser();
    }
}
